﻿using System;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using DSkin.Forms;
using HttpCodeLib;
using Newtonsoft.Json.Linq;

namespace QQLogin
{
    public partial class FrmQqLogin : Skin_VS_Light
    {
        private string gtk, uin, cookies;
        private XJHTTP xjHttp = new XJHTTP();
        public FrmQqLogin()
        {
            InitializeComponent();
        }

        private void webBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            if (!e.Url.AbsoluteUri.StartsWith("https://qun.qq.com/")) return;
            if (!CheckLogin(webBrowser.Document.Cookie)) return;
            webBrowser.Visible = false;
            ThreadPool.QueueUserWorkItem((s) =>
            {
                try
                {
                    var helper = new HttpHelpers();
                    var item = new HttpItems
                    {
                        URL = "http://film.qq.com/weixin/topic/binding.html",
                        Cookie = cookies
                    };
                    helper.GetHtml(item);
                    item = new HttpItems
                    {
                        URL = $"http://vip.video.qq.com/fcgi-bin/comm_cgi?name=bindphone&otype=json&cmd=1&_t=5&sid=&code=&act=&from=aphone&_=1531927781625&callback=Zepto1531927781560",
                        Cookie = cookies,
                        Referer = "http://film.qq.com/weixin/topic/binding.html",
                        UserAgent = "Mozilla/5.0 (Linux; Android 6.0; PRO 6 Build/MRA58K; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/53.0.2785.49 Mobile MQQBrowser/6.2 TBS/043221 Safari/537.36 V1_AND_SQ_7.0.0_676_YYB_D QQ/7.0.0.3135 NetType/WIFI WebP/0.3.0 Pixel/1080"
                    };
                    var html = helper.GetHtml(item).Html.Replace("Zepto1531927781560(", "").Replace(");", "");
                    var obj = JObject.Parse(html);
                    if (obj["result"]["code"].ToString() != "0")
                    {
                        PublicInfo.QQ = uin;
                        PublicInfo.Gtk = gtk;
                        PublicInfo.Cookies = cookies;
                        Invoke((Action)(() => DialogResult = DialogResult.OK));
                        return;
                    }
                    Invoke((Action)(() =>
                    {
                        DSkinMessageBox.Show("该账号已经绑定！");
                        webBrowser.Navigate("https://xui.ptlogin2.qq.com/cgi-bin/xlogin?appid=715030901&daid=73&pt_no_auth=1&s_url=http%3A%2F%2Fqun.qq.com%2F");
                        webBrowser.Visible = true;
                        webBrowser.Document.Cookie = null;
                        cookies = "";
                    }));
                }
                catch (Exception ex)
                {
                    Invoke((Action)(() =>
                    {
                        DSkinMessageBox.Show(ex.Message);
                    }));
                }
            });
        }

        private bool CheckLogin(string c)
        {
            var cookieList = xjHttp.GetAllCookie(xjHttp.StringToCookie("qun.qzone.qq.com", c));
            var skey = cookieList.FirstOrDefault(cookie => cookie.Name == "skey")?.Value;
            if (skey == "")
                return false;
            gtk = GetGtk(skey);
            uin = cookieList.FirstOrDefault(cookie => cookie.Name == "p_uin")?.Value.Replace("o", "").TrimStart('0');
            cookieList.ForEach(cl => cookies += (cl.Name + "=" + cl.Value + ";"));
            return gtk != "" && uin != "";
        }

        public static string GetGtk(string value)
        {
            var a = 5381;
            for (int s = 0, f = value.Length; s < f; ++s)
            {
                a += (a << 5) + ToUnicode(value, s);
            }
            return (a & 2147483647) + "";
        }

        static int ToUnicode(string str, int s)
        {
            return str[s];
        }
    }
}
